<?php

class Public_Profile_EditAction extends BlogPublicBaseAction
{
    public function executeRead(AgaviRequestDataHolder $rd)
    {
        /* @var $user BlogUser */
        $user = $this->getContext()->getUser();
        if (!$user->isAuthenticated() || $user->hasRole('blog-owner')) {
            return array('Public', 'Error404Success');
        }
        
        return 'Input';
    }
    
    public function executeWrite(AgaviRequestDataHolder $rd)
    {
        /* @var $user BlogUser */
        $user = $this->getContext()->getUser();
        $params = $rd->getParameters();
        $vm = $this->getContainer()->getValidationManager();
        if (!$user->isAuthenticated()) {
            return array('Public', 'Error404Success');
        }
        
        $user_id = $user->getAttribute('user_id');
        /* @var $users_model Admin_UsersModel */
        $users_model = $this->getContext()->getModel('Users', 'Admin');
        $sys_user = $users_model->getUser($user_id);
        if (is_null($sys_user)) {
            return array('Public', 'Error404Success');
        }
        
        
        $new_password = null;
        // update user password if required
        if ($user->getAttribute('user_type') == 'plain' && isset($params['current_password'])
            && isset($params['new_password_1'])) 
        {
            // check old password
            if (!$users_model->checkUserPassword($user->getAttribute('username'), $params['current_password'])) {
                $vm->setError('current_password', 'Invalid current password.');
                return 'Error';
            }
            
            $new_password = $params['new_password_1'];
        }
        
        $lo_website = strtolower($params['website']);
        if ($lo_website != '' && strpos($lo_website, 'http://') !== 0 && strpos($lo_website, 'https://') !== 0) {
            $params['website'] = 'http://'.$params['website'];
        }
        
        // update system user and also update session data
        $users_model->updateUserData($sys_user, $params['display_name'], $params['email'], 
            $params['website'], $new_password, null);
        $user->reloadUser();
        
        return 'Success';
    }
    
	/**
	 * Returns the default view if the action does not serve the request
	 * method used.
	 *
	 * @return     mixed <ul>
	 *                     <li>A string containing the view name associated
	 *                     with this action; or</li>
	 *                     <li>An array with two indices: the parent module
	 *                     of the view to be executed and the view to be
	 *                     executed.</li>
	 *                   </ul>
	 */
	public function getDefaultViewName()
	{
		return 'Input';
	}
	
	public function isSecure()
	{
	    return true;
	}
	
	public function getCredentials()
	{
	    return array('profile.edit-own');
	}
}

?>